import pathlib
import sys
import time

import requests
from PySide6.QtCore import Qt
from PySide6.QtWidgets import (QApplication, QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout, QFrame, QComboBox,
                               QListWidget, QListWidgetItem, QTableWidget, QTableWidgetItem, QFileDialog, QMessageBox)
from PySide6.QtGui import QIcon

from widgets.wechat_info import WechatInfoWidget

from events.start_wechat import StartWechatThread
from events.wechat_user import WechatUserInfoThread
from events.linkman_list import WechatLinkmanListThread
from events.chatroom_members import ChatroomMembersThread
from events.export_excel import ExportExcelThread


from settings import HOST


class Robot(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('微信机器人')
        self.setWindowIcon(QIcon('src/wechat.png'))
        m_layout = QVBoxLayout(self)

        self.launch_wechat_btn = QPushButton(self)
        self.launch_wechat_btn.setText('启动微信')
        self.launch_wechat_btn.clicked.connect(self.launch_wechat)
        hl1 = QHBoxLayout(self)
        hl1.addWidget(self.launch_wechat_btn)

        self.launch_wechat_label = QLabel(self)
        self.launch_wechat_label.setText('微信已登录')
        hl1.addWidget(self.launch_wechat_label)

        hl1.addStretch()
        m_layout.addLayout(hl1)

        hl2 = QHBoxLayout(self)
        self.wechat_user_info = WechatInfoWidget(self)
        hl2.addWidget(self.wechat_user_info)

        hl2.addStretch()

        h_line1 = QFrame(self)
        h_line1.setFrameShape(QFrame.Shape.HLine)
        h_line1.setFrameShadow(QFrame.Shadow.Sunken)
        m_layout.addWidget(h_line1)

        m_layout.addLayout(hl2)

        h_line2 = QFrame(self)
        h_line2.setFrameShape(QFrame.Shape.HLine)
        h_line2.setFrameShadow(QFrame.Shadow.Sunken)
        m_layout.addWidget(h_line2)

        hl3 = QHBoxLayout(self)
        self.actions_widget = QWidget(self)
        ac_layout = QHBoxLayout(self.actions_widget)

        self.linkman_type_combox = QComboBox(self)
        ac_layout.addWidget(self.linkman_type_combox)
        self.linkman_list_button = QPushButton(self)
        self.linkman_list_button.setText('拉取')
        self.linkman_list_button.clicked.connect(self.pull_linkman_list)
        ac_layout.addWidget(self.linkman_list_button)
        self.export_friends_button = QPushButton('导出好友')
        self.export_friends_button.setDisabled(True)
        self.export_friends_button.clicked.connect(self.export_friends)
        ac_layout.addWidget(self.export_friends_button)
        ac_layout.addStretch()

        self.chatroom_members_btn = QPushButton(self)
        self.chatroom_members_btn.setText('获取成员列表')
        self.chatroom_members_btn.clicked.connect(self.pull_chatroom_members)
        self.chatroom_members_btn.setDisabled(True)
        ac_layout.addWidget(self.chatroom_members_btn)
        self.chatroom_members_remark_btn = QPushButton(self)
        self.chatroom_members_remark_btn.setText('显示备注')
        self.chatroom_members_remark_btn.clicked.connect(self.remark_chatroom_members)
        self.chatroom_members_remark_btn.setDisabled(True)
        ac_layout.addWidget(self.chatroom_members_remark_btn)
        self.export_chatroom_members_btn = QPushButton(self)
        self.export_chatroom_members_btn.setText('导出成员列表')
        self.export_chatroom_members_btn.clicked.connect(self.export_chatroom_members)
        self.export_chatroom_members_btn.setDisabled(True)
        ac_layout.addWidget(self.export_chatroom_members_btn)

        hl3.addWidget(self.actions_widget)
        m_layout.addLayout(hl3)

        h_line3 = QFrame(self)
        h_line3.setFrameShape(QFrame.Shape.HLine)
        h_line3.setFrameShadow(QFrame.Shadow.Sunken)
        m_layout.addWidget(h_line3)

        self.content_widget = QWidget(self)
        cont_layout = QHBoxLayout(self.content_widget)
        self.linkman_list = QListWidget(self)
        self.linkman_list.setMaximumWidth(300)
        self.linkman_list.currentItemChanged.connect(self.list_current_item_changed)
        cont_layout.addWidget(self.linkman_list)
        self.cnt_table = QTableWidget(self)
        cont_layout.addWidget(self.cnt_table)

        self.content_widget.setLayout(cont_layout)

        m_layout.addWidget(self.content_widget)

        # m_layout.addStretch()
        self.setLayout(m_layout)

        self.check_launched()

        self.init_data()

    def init_data(self):
        self.linkman_type_combox.addItem(QIcon('src/haoyou.png'), '好友', {'type': 1, 'name': '好友'})
        self.linkman_type_combox.addItem(QIcon('src/qunliao.png'), '群列表', {'type': 2, 'name': '群聊'})
        self.linkman_type_combox.addItem(QIcon('src/gzhao.png'), '公众号', {'type': 3, 'name': '公众号'})
        self.linkman_type_combox.addItem(QIcon('src/qita.png'), '其他', {'type': 4, 'name': '其他'})

    def check_launched(self):
        try:
            r = requests.post(HOST, json={'type': 1})
            if r.json()['errno'] == 0:
                self.launch_wechat_success()
        except Exception as e:
            print(e)
            self.launch_wechat_btn.show()
            self.launch_wechat_label.hide()
            self.actions_widget.hide()
            pass

    def launch_wechat(self):
        self.launch_wechat_btn.setText('启动中...')
        self.launch_wechat_btn.setDisabled(True)

        thread = StartWechatThread(self)
        thread.error_signal.connect(self.launch_wechat_error)
        thread.success_signal.connect(self.launch_wechat_success)
        thread.finished.connect(thread.deleteLater)
        thread.start()

    def launch_wechat_error(self, err):
        self.launch_wechat_btn.setDisabled(False)
        self.launch_wechat_btn.setText('启动微信')
        self.launch_wechat_btn.show()
        self.launch_wechat_label.hide()

        self.wechat_user_info.hide()

    def launch_wechat_success(self):
        self.launch_wechat_btn.setDisabled(False)
        self.launch_wechat_btn.setText('启动微信')
        self.launch_wechat_btn.hide()
        self.launch_wechat_label.setText('微信已登录')
        self.launch_wechat_label.show()

        self.get_wechat_userinfo()
        self.wechat_user_info.show()
        self.actions_widget.show()

    def get_wechat_userinfo(self):
        thread = WechatUserInfoThread(self)
        thread.finished.connect(thread.deleteLater)
        thread.success_signal.connect(self.get_wechat_userinfo_success)
        thread.error_signal.connect(self.get_wechat_userinfo_error)
        thread.start()

    def get_wechat_userinfo_error(self):
        pass

    def get_wechat_userinfo_success(self, data):
        self.wechat_user_info.set_info(data)

    def pull_linkman_list(self):
        comm = self.linkman_type_combox.currentData()
        thread = WechatLinkmanListThread(self)
        thread.set_pull_type(comm['type'])
        thread.finished.connect(thread.deleteLater)
        thread.success_signal.connect(self.pull_linkman_success)
        thread.error_signal.connect(self.pull_linkman_error)
        thread.start()

    def pull_linkman_success(self, data):
        self.linkman_list.clear()
        comm = self.linkman_type_combox.currentData()
        no_name_index = 1
        for man in data['list']:
            list_item = QListWidgetItem()
            list_item.setData(Qt.UserRole, man)
            show_name = man['nick_name']
            if man['remark']:
                show_name += '({})'.format(man['remark'])
            if not show_name:
                show_name = '{}{}'.format(comm['name'], no_name_index)
                no_name_index += 1
            list_item.setText(show_name)
            list_item.setData(1, man)
            self.linkman_list.addItem(list_item)

        if comm['type'] == 1:
            self.export_friends_button.setDisabled(False)
        else:
            self.export_friends_button.setDisabled(True)

    def pull_linkman_error(self, err):
        pass

    def export_friends(self):
        friends_data = []
        for row in range(self.linkman_list.count()):
            item_data = self.linkman_list.item(row).data(Qt.UserRole)
            # remark = item_data['remark']
            # if not remark.lower().startswith('o'):
            #     continue
            friends_data.append({
                '序号': row + 1,
                '昵称': item_data['nick_name'],
                '微信号': item_data['wx_account'],
                '微信ID': item_data['wx_id'],
                '备注': item_data['remark'],
                '公司': '',
                '平台': '',
                '姓名': '',
                '手机号': '',
            })

        # 选择保存的文件夹
        folder = QFileDialog.getExistingDirectory(self)
        if not folder:
            return QMessageBox.information(self, '提示', '请选择保存文件的位置!')
        filename = pathlib.Path(folder).joinpath('好友数据_{}.xlsx'.format(int(time.time())))
        self.export_table_data(friends_data, filename)

    def list_current_item_changed(self, curr, prev):
        comm = self.linkman_type_combox.currentData()
        if not curr or comm['type'] != 2:
            self.cnt_table.clearContents()
            self.chatroom_members_btn.setDisabled(True)
            self.export_chatroom_members_btn.setDisabled(True)
            return

        self.chatroom_members_btn.setDisabled(False)
        self.cnt_table.setColumnCount(4)
        self.cnt_table.setHorizontalHeaderLabels(['昵称', '微信号', '微信ID', '备注'])

    def pull_chatroom_members(self):
        curr_item = self.linkman_list.currentItem()
        curr_data = curr_item.data(1)
        if not curr_data:
            return
        thread = ChatroomMembersThread(self)
        thread.set_chatroom(curr_data['wx_id'])
        thread.finished.connect(thread.deleteLater)
        thread.success_signal.connect(self.pull_chatroom_members_success)
        thread.error_signal.connect(self.pull_chatroom_members_error)
        thread.start()

    def pull_chatroom_members_success(self, data):
        self.cnt_table.setRowCount(len(data['list']))
        for row, man in enumerate(data['list']):
            man['remark'] = ''
            for col, key in enumerate(['nick_name', 'wx_account', 'wx_id', 'remark']):
                self.cnt_table.setItem(row, col, QTableWidgetItem(man[key]))
        self.chatroom_members_remark_btn.setDisabled(False)
        self.export_chatroom_members_btn.setDisabled(False)

    def pull_chatroom_members_error(self, err):
        pass

    def remark_chatroom_members(self):
        # 获取好友列表，进行备注
        try:
            r = requests.post(HOST, json={'type': 5, 'pull_type': 1})
            data = r.json()
            if data['errno'] == 0:
                members = data['data']['list']
            else:
                members = []
        except Exception as e:
            pass

        else:
            members_dict = {
                m['wx_id']: m['remark']
                for m in members
            }
            for row in range(self.cnt_table.rowCount()):
                wx_id_item = self.cnt_table.item(row, 2)
                wx_id = wx_id_item.text()
                if wx_id:
                    remark_item = self.cnt_table.item(row, 3)
                    remark_item.setText(members_dict.get(wx_id, ''))

    def get_current_tabel_data(self):
        row_count = self.cnt_table.rowCount()
        col_count = self.cnt_table.columnCount()
        # 获取表头
        headers_list = [self.cnt_table.horizontalHeaderItem(col).text() for col in range(col_count)]
        data_list = []
        for row in range(row_count):
            row_data = {}
            for col in range(col_count):
                row_data[headers_list[col]] = self.cnt_table.item(row, col).text()
            data_list.append(row_data)

        return data_list

    def export_chatroom_members(self):
        table_data = self.get_current_tabel_data()
        # 选择保存的文件夹
        folder = QFileDialog.getExistingDirectory(self)
        if not folder:
            return QMessageBox.information(self, '提示', '请选择保存文件的位置!')
        filename = pathlib.Path(folder).joinpath('微信机器人表格数据_{}.xlsx'.format(int(time.time())))
        self.export_table_data(table_data, filename)

    def export_table_data(self, table_data, filename):
        thread = ExportExcelThread(self)
        thread.set_data(table_data)
        thread.set_filename(filename)
        thread.finished.connect(thread.deleteLater)
        thread.success_signal.connect(self.export_data_success)
        thread.error_signal.connect(self.export_data_error)
        thread.start()

    def export_data_success(self, msg):
        QMessageBox.information(self, '导出成功', str(msg))

    def export_data_error(self, err):
        QMessageBox.warning(self, '导出失败！', str(err))


if __name__ == '__main__':
    app = QApplication([])
    window = Robot()
    window.resize(1366, 768)
    window.show()
    sys.exit(app.exec())

    # pyinstaller --name="WechatRobot" --icon="src/wechat.png" --add-data="WeChatApi.dll:." --add-data="inject_tool.exe:." --add-data="src:src" --windowed robot.py
